package com.videri.match.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;


public class CreateAccount extends MatchSink{
	public static MatchSinkInfo init() {
		return new MatchSinkInfo("Create Account") {
			public MatchSink createInstance(){
				return new CreateAccount();
			}

			public String getColor(){
				return "#AE2F2D";
			}
		};
	}

	private VerticalPanel mySignUp;

	/**
	 * This will create a new CreateAccount sink
	 */
	public CreateAccount(){
		initialize();
		initWidget(mySignUp);
	}

	private void initialize(){
		mySignUp = new VerticalPanel();
		FlexTable form = new FlexTable();
		mySignUp.add(form);

		Label handleLabel = new Label("Username:");
		form.setWidget(0, 0, handleLabel);

		Label passLabel = new Label("Password:");
		form.setWidget(1, 0, passLabel);

		Label firstLabel = new Label("First Name:");
		form.setWidget(2, 0, firstLabel);

		Label lastLabel = new Label("Last Name:");
		form.setWidget(3, 0, lastLabel);

		Label emailLabel = new Label("Email Address:");
		form.setWidget(4, 0, emailLabel);

		final TextBox handleText = new TextBox();
		form.setWidget(0, 1, handleText);

		final PasswordTextBox pswdText =  new PasswordTextBox();
		form.setWidget(1, 1, pswdText);

		final TextBox firstText = new TextBox();
		form.setWidget(2, 1, firstText);

		final TextBox lastText = new TextBox();
		form.setWidget(3, 1, lastText);

		final TextBox emailText = new TextBox();
		form.setWidget(4, 1, emailText);

		Button signUpButton = new Button();
		form.setWidget(5, 1, signUpButton);

		signUpButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				String[] info = new String[5];
				info[0] = lastText.getText();
				info[1] = firstText.getText();
				info[2] = handleText.getText();
				info[3] = pswdText.getText();
				info[4] = emailText.getText();

				if(!(CreateAccount.isValid(info))){
					//error messages displayed in isNotValid
					//just break here.
				}
				else {
					//register user

					//This is the awesome code right here!!!
					VideriMatchServiceAsync videriServices = (VideriMatchServiceAsync)GWT.create(VideriMatchService.class);

					ServiceDefTarget endpoint = (ServiceDefTarget) videriServices;
					String moduleRelativeURL = GWT.getModuleBaseURL()+"matching";
					endpoint.setServiceEntryPoint(moduleRelativeURL);

					AsyncCallback callback = new AsyncCallback() {                
						public void onSuccess(Object result) {
							//user registered
							Boolean temp = (Boolean)result;
							boolean created = temp.booleanValue();
							//if username is already taken...
							if(!(created)){
								Window.alert("Server Error in processing your application.  Please Try Again");
							}
							//else-- Success!
							else{
								Window.alert("Account successfully created");
								//Clear all fields
								handleText.setText("");
								pswdText.setText("");
								firstText.setText("");
								lastText.setText("");
								emailText.setText("");
								
								//proceed to login
								mySignUp.add(new HTMLPanel("Proceed to login."));
								
								//TODO: Auto login and navigate to homepage
							}
						}                
						public void onFailure(Throwable caught) {                    
							Window.alert("Problem connecting to server during registration.");              
						}            
					};
					videriServices.createNewUser(info, callback);
				}
			}

		}
		);
		//TODO: add keyboard listener so hitting return works the same as pressing login.
		signUpButton.setText("Create Account");
	};	

	public static boolean isValid(String[] info) {
		boolean valid = true;
		//Check Password (length > 5)
		if(info[3].length() < 6){
			Window.alert("Password must be more than 5 characters long");
			valid = false;
		}
		//Check Username (length > 4)
		if(info[2].length() < 5){
			Window.alert("Username must be atleast 5 Characters long");
			valid = false;
		}
		//Check email (validity)
		if(!((info[4]).matches(".*@.*"))){
			Window.alert("Invalid email address");
			valid = false;
		}
		//Check first name (length > 1)
		if(info[1].length() < 2){
			Window.alert("Please enter a valid first name.");
			valid = false;
		}
		//Check last name (length > 1)
		if(info[0].length() < 2){
			Window.alert("Please enter a valid last name.");
			valid = false;
		}
		return valid;
	}
}
